<?php

namespace app\airobot\controller;

use app\airobot\CommonLogic;
use app\airobot\model\BattleBox;
use app\airobot\model\OriginBattleConfig;
use app\airobot\model\OriginForge;
use app\airobot\model\OriginRobotSpinConfig;
use app\airobot\model\UserModel;
use think\admin\Controller;
use think\db\exception\DbException;
use think\facade\Db;
use ZipArchive;

/**
 * 超管系统-赔率监控Forge
 * Class Banner
 * @package app\airobot\controller
 */
class MonitorForge extends Controller
{
    private $table = 'monitor_forge';
    public $commonLogic;

    /**
     * 赔率监控Forge
     * @auth true
     */
    public function index()
    {
        $this->commonLogic = new CommonLogic();
        $this->title = '赔率监控Forge';
        $query = $this->_query($this->table);
        if (isset($_GET['exec_time']) && $_GET['exec_time'] != "") {
            $dayArr = explode(" - ", $_GET['exec_time']);
            if (count($dayArr) == 2) {
                $query->where('date', '>=', $dayArr[0]);
                $query->where('date', '<=', $dayArr[1]);
            }
        }
        $data = $query->select()->toArray();
        $data = $this->dealData($data);

        $this->list = $data;
        $this->fetch();
    }

    protected function dealData(array $data): array
    {
        $dataMap = [];
        foreach ($data as $vo) {
            $dataMap[$vo['product_id']][] = $vo;
        }

        $dataArr = [];
        foreach ($dataMap as $boxId => $dataList) {
            $dataItem = [];
            $dataItem["product_id"] = $boxId;
            $dataItem["spin_amount"] = 0;
            $dataItem["enter_count"] = 0;
            $dataItem["spin_count"] = 0;
            $dataItem["total_spin_amount"] = 0;
            $dataItem["total_win_amount"] = 0;
            $userIdMap = [];
            foreach ($dataList as $vo) {
                $userIds = explode("|", $vo['user_ids']);
                foreach ($userIds as $userId) {
                    $userIdMap[$userId] = $userId;
                }
                $dataItem["spin_amount"] += $vo['spin_amount'];
                $dataItem["enter_count"] += $vo['enter_count'];
                $dataItem["spin_count"] += $vo['spin_count'];
                $dataItem["total_spin_amount"] += $vo['total_spin_amount'];
                $dataItem["total_win_amount"] += $vo['total_win_amount'];
            }
            $dataItem["user_count"] = count($userIdMap);
            $dataItem["avg_user_spin_times"] = $dataItem["spin_count"] / $dataItem["user_count"];
            $dataItem["avg_box_spin_times"] = $dataItem["spin_count"] / $dataItem["enter_count"];
            $dataItem["user_odds"] = $dataItem["total_win_amount"] / $dataItem["total_spin_amount"];
            $dataItem["system_profit_amount"] = $dataItem["total_spin_amount"] - $dataItem["total_win_amount"];
            $dataArr[] = $dataItem;
        }

        $data = [];
        $this->commonLogic = new CommonLogic();
        foreach ($dataArr as $vo) {
            $vo["spin_amount"] = $this->commonLogic->DealAmount($vo['spin_amount']);
            $vo["user_count"] = number_format($vo["user_count"], 0);
            $vo["enter_count"] = number_format($vo["enter_count"], 0);
            $vo["spin_count"] = number_format($vo["spin_count"], 0);
            $vo["total_spin_amount"] = $this->commonLogic->DealAmount($vo['total_spin_amount']);
            $vo["total_win_amount"] = $this->commonLogic->DealAmount($vo['total_win_amount']);
            $vo["avg_user_spin_times"] = number_format($vo["avg_user_spin_times"], 2);
            $vo["avg_box_spin_times"] = number_format($vo["avg_box_spin_times"], 2);
            $vo["user_odds"] = number_format($vo["user_odds"], 4);
            $vo["system_profit_amount"] = $this->commonLogic->DealAmount($vo['system_profit_amount']);
            $data[] = $vo;
        }
        return $data;
    }

    /**
     * 导出文件
     * @auth true
     */
    public function export()
    {
        // 获取数据
        $query = Db::table('monitor_forge');
        if (isset($_GET['exec_time']) && $_GET['exec_time'] != "") {
            $dayArr = explode(" - ", $_GET['exec_time']);
            if (count($dayArr) == 2) {
                $query->where('date', '>=', $dayArr[0]);
                $query->where('date', '<=', $dayArr[1]);
            }
        }
        $list = $query->select()->toArray();
        $list = $this->dealData($list);

        // 设置 CSV 文件的名字
        $filename = "monitor_forge.csv";
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="' . $filename . '";');
        $output = fopen('php://output', 'w');

        // 写入 CSV 头部
        fputcsv($output, ['商品ID', '单次花费', '用户数量', '进入次数', 'spin次数', '用户消耗', '用户赢钱', '人均spin次数', '场均spin次数', '用户赔率', '盈利']);

        // 写入数据行
        foreach ($list as $v) {
            fputcsv($output, [$v['product_id'], $v['spin_amount'], $v['user_count'], $v['enter_count'], $v['spin_count'], $v['total_spin_amount'], $v['total_win_amount'], $v['avg_user_spin_times'], $v['avg_box_spin_times'], $v['user_odds'], $v['system_profit_amount']]);
        }

        // 关闭输出流
        fclose($output);
    }

    /**
     * 批量删除
     * @auth true
     */
    public function remove()
    {
        try {
            Db::startTrans();

            Db::table("monitor_forge")->where('id', '>', 0)->delete();
            Db::table("user_spin")->where(["battle_id" => 0, "spin_type" => 2])->delete();

            // 如果一切正常，提交事务
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            error_log(var_export($exception->getMessage(), true) . "\n", 3, "/tmp/qp.log");
            $this->error('清空失败');
        }

        $this->success('清空成功');
    }
}